<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CartController extends Controller
{
    //
    public function show(Request $request)
    {
        $user = $request -> session() -> get('user');
        if(empty($user)){
            return redirect('/login');
        }
        $goods = DB::table('bro_goods as a') -> join('bro_cart as b','a.id','=','b.goods_id')->where('b.uid',$user->id) -> get();
        $good = DB::table('bro_goods') -> orderBy(DB::raw('RAND()')) ->take(4)->where('tuijian',1)->get();
        return view('home.cart.cart',['goods' => $goods,'good' => $good,'user'=>$user]);
    }

    public function balance(Request $request)
    {
        $data = $request -> except('_token');
        $cart_id = explode(',',$data['shop_id']);
        $shop_num_arr = explode(',',$data['shop_num']);
        $user = $request -> session() -> get('user');
        session(['cart_id' => $cart_id]);//购物车ID存入session
        if(empty($user)){
            return redirect('/login');
        }
        $shop_id = [];
        //遍历查询商品ID
        foreach($cart_id as $cval)
        {
            $cart_g = DB::table('bro_cart') -> where('id',$cval) -> first();
            $shop_id []= $cart_g -> goods_id;
        }
        // dd($shop_id);
        $i=0;

        $order_data['ordernum'] = time().rand(1000,9999);

        $orderprice = [];

        foreach ($shop_id as $shop_val)
        {
            $good = DB::table('bro_goods') ->where('id',$shop_val)-> first();

            //判断 商品的数量是否大于 购物车传过来的数量

            $shop_num = $shop_num_arr[$i];

            // dd($good);

            if($good->num > $shop_num){
                //生成订单 插入商品ID 商品数量
                $orderprice[] = $good->price*$shop_num;
                
            }
            $goods['ordernum'] = $order_data['ordernum'];
            $goods['goods_id'] = $good -> id;
            $goods['goodsname'] = $good -> goods_name;
            $goods['goods_pic'] = $good -> goods_pic;
            $goods['price'] = $good -> price;
            $goods['num'] = $shop_num;
            // dd($goods);
            //添加商品详情
            DB::table('bro_indent') -> insert($goods);
            $i++;
        }
        
        //生成订单
        $order['indent_price'] = array_sum($orderprice);
        $order['goods_price'] = array_sum($orderprice);
        $order['atime'] = time();
        $order['ordernum'] = $order_data['ordernum'];
        $order['uname'] = $user -> username;
        $order['uid'] = $user -> id;
        session(['ordernum' => $order_data['ordernum']]);//订单编号存入SESSION
        DB::table('bro_order') ->insert($order);
        $cartid = $data['shop_id'];
        $num = $data['shop_num'];
        // dd($order);
        return redirect("/order_add/$cartid/$num");

    }

    //生成订单
    public function add(Request $request,$cartid,$num)
    {   
        $title = '提交订单';
        //会话跟踪
        $user = $request -> session() ->  get('user');
        // $ordernum = $request -> session() -> get('ordernum');
        // dd($order);
        //====获取提交的商品ID 和 数量
        // $cartid = $cart_id;
        // $num = $num;
        // dd($cartid,$num);
        
        $cart_id = explode(',',$cartid);
        $shop_num_arr = explode(',',$num);
        // dd($shop_num_arr,$cart_id);
        $cart_gs = [];
        foreach($cart_id as $k => $cval)
        {
            $cart_g = DB::table('bro_cart') -> where('id',$cval) -> first();
            $goods = DB::table('bro_goods') -> where('id',$cart_g -> goods_id) ->select('price','goods_pic','goods_name') -> first();
            $cart_g -> price = $goods -> price;
            $cart_g -> goods_pic = $goods -> goods_pic;
            $cart_g -> goods_name = $goods -> goods_name;
            $cart_gs []= $cart_g;
            //减库存
            DB::table('bro_goods') -> where('id',$cart_g -> goods_id) -> decrement('num',$shop_num_arr[$k]);
            //加销量
            DB::table('bro_goods') -> where('id',$cart_g -> goods_id) -> increment('sellnum',$shop_num_arr[$k]);
            // // 删除购物车
            // DB::table('bro_cart') -> where(['goods_id'=>$cart_g -> goods_id,'uid'=>$user->id]) -> delete();

        }
        //计算商品总额 和 订单的总额
        $s_price = [];
        foreach($cart_gs as $k => $cvl)
        {
            $s_price[] = $cvl -> price*$shop_num_arr[$k];
        }
        
        $sum_p = array_sum($s_price);//订单总额
        $sum_g = array_sum($shop_num_arr);//选中了几件商品
        //
        //
        // dd($s_price);
        //友情链接
        $link = DB::table('bro_link') -> orderBy('order', 'desc') -> get();
        //========获取收货人地址=======
        $address= DB::table('bro_address') -> where('status',1) ->where('uid',$user -> id) -> first();
        if(empty($address))
        {
            //如果 无默认地址 选最早的一条
            $address = DB::table('bro_address') -> where('status',0) ->where('uid',$user -> id) -> take(1) -> first();
            if(!empty($address))
            {
            //获取剩余地址
            $address2 = DB::table('bro_address') -> where('status',0) ->where('uid',$user -> id) -> whereNotIn('id',[$address -> id]) -> get();
          // dd($address);
          }
        }else{
            //=====获取不是默认地址
            $address2 = DB::table('bro_address') -> where('status',0) -> where('uid',$user -> id) -> get();
        }

      
        if(empty($address2))
      {
        $address2 = '';
        return view('home.order.order',['title' => $title,'user' => $user,'link' => $link,'address' => $address,'address2' => $address2,'cart_gs' => $cart_gs,'num' => $shop_num_arr,'s_price' => $s_price,'sum_p' => $sum_p,'sum_g' => $sum_g,'cartid' => $cartid,'gnum' => $num]);
      }else{
        return view('home.order.order',['title' => $title,'user' => $user,'link' => $link,'address' => $address,'address2' => $address2,'cart_gs' => $cart_gs,'num' => $shop_num_arr,'s_price' => $s_price,'sum_p' => $sum_p,'sum_g' => $sum_g,'cartid' => $cartid,'gnum' => $num]);
      }
    }

    //添加地址
    public function insert(Request $request)
    {   
        $data = $request -> except('_token');
        $user = $request -> session() ->  get('user');
        $data['uid'] = $user -> id;
        //=====添加收货地址=======
        $res = DB::table('bro_address') -> insert($data);
        
        return response() -> json($res);    
    }
    //改变默认地址
    public function change(Request $request)
    {
        $id = $request ->all();
      $user = $request -> session() ->  get('user');
      $data['status'] = 0;
        
      $res = DB::table('bro_address') -> where(['uid'=>$user->id,'status'=> 1]) -> update($data);
      
      $a = DB::table('bro_address') -> where(['id'=>$id,'uid'=>$user->id]
      ) -> update(['status' => 1]);
      return response() -> json($a);
    }
    //删除地址
    public function delete(Request $request)
    {
      $id = $request -> all();

      $res = DB::table('bro_address') -> where('id',$id) -> delete();
      return response() -> json($res);

    }
    // 提交订单
    public function sub(Request $request)
    {

        //获取地址ID
        $address_id = $request -> all();
        if(!$address_id)
        {
            return back();
        }
        //删除购物车
        $user = $request -> session() -> get('user');
        $cart_id = $request -> session() -> get('cart_id');
        foreach($cart_id as $val)
        {
            DB::table('bro_cart') -> where(['id'=>$val,'uid'=>$user->id]) -> delete();
        }
        //查询地址
        $adds = DB::table('bro_address') -> where('id',$address_id) -> first();
        $address['utname'] = $adds -> utname;
        $address['uphone'] = $adds -> uphone;
        $address['post'] = $adds -> post;
        $address['address'] = $adds -> address;
        //获取订单号
        $ordernum = $request -> session() -> get('ordernum');

        //添加收货地址
        $res = DB::table('bro_order') -> where('ordernum',$ordernum) -> update($address);
        
        return response() -> json($res);
    }
    //ajax删除
    public function delete1(Request $request)
    {
        $id = $request -> all();

        DB::table('bro_cart') -> where('id',$id) -> delete();
        return response() -> json($id);
    }
}
